package hhm.android.account

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.trello.rxlifecycle4.RxLifecycle
import com.trello.rxlifecycle4.android.ActivityEvent
import siau.android.http.model.ForgetPasswordRequest
import siau.android.http.model.MobileRequest
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import siau.android.base.HttpHelper
import java.util.concurrent.TimeUnit

class ForgetPasswordViewModel : ViewModel() {

    var canGetCode = false
    var canClickBtn = MutableLiveData(false)
    var hasGetCode = MutableLiveData(false)
    var showPassword = false

    var countDownNumber = MutableLiveData(60)
    private var subscribe: Disposable? = null
    var errorString = MutableLiveData<String>()
    var passwordChange = MutableLiveData(false)

    fun startCountDown(o: Observable<ActivityEvent>, phone: String) {
        subscribe = Observable.interval(0,1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe {
            val t = 59 - it.toInt()
            if (t == 0) {
                countDownNumber.value = 60
                hasGetCode.value = false
                subscribe?.dispose()
            } else {
                countDownNumber.value = t
            }
        }

        val request = MobileRequest(phone, 4)
        HttpHelper().getCaptcha(request)?.compose(RxLifecycle.bindUntilEvent(o, ActivityEvent.STOP))?.subscribe({

        }, {
            errorString.value = it.message
        })
    }

    fun changePassword(o: Observable<ActivityEvent>, phone: String, code: String, password: String) {
        val r = ForgetPasswordRequest(password, code, phone)
        HttpHelper().forgetPassword(r)?.compose(RxLifecycle.bindUntilEvent(o, ActivityEvent.STOP))?.subscribe({
            passwordChange.value = true
        }, {
            errorString.value = it.message
        })
    }

    fun finish() {
        subscribe?.dispose()
    }
}